//数据访问对象
import 'package:sqflite/sqflite.dart';
import '../database/database_helper.dart';
import '../models/todo.dart';

class TodoDao {
  final DatabaseHelper _databaseHelper = DatabaseHelper();

  Future<int> insertTodo(Todo todo) async {
    final db = await _databaseHelper.database;
    return await db.insert('todos', todo.toMap());
  }

  Future<List<Todo>> getAllTodos() async {
    final db = await _databaseHelper.database;
    final List<Map<String, dynamic>> maps = await db.query('todos');
    return List.generate(maps.length, (i) {
      return Todo.fromMap(maps[i]);
    });
  }

  Future<List<Todo>> getCompletedTodos() async {
    final db = await _databaseHelper.database;
    final List<Map<String, dynamic>> maps =
        await db.query('todos', where: 'isCompleted = ?', whereArgs: [1]);
    return List.generate(maps.length, (i) {
      return Todo.fromMap(maps[i]);
    });
  }

  Future<List<Todo>> getPendingTodos() async {
    final db = await _databaseHelper.database;
    final List<Map<String, dynamic>> maps =
        await db.query('todos', where: 'isCompleted = ?', whereArgs: [0]);
    return List.generate(maps.length, (i) {
      return Todo.fromMap(maps[i]);
    });
  }

  Future<int> updateTodo(Todo todo) async {
    final db = await _databaseHelper.database;
    return await db
        .update('todos', todo.toMap(), where: 'id = ?', whereArgs: [todo.id]);
  }

  Future<int> deleteTodo(int id) async {
    final db = await _databaseHelper.database;
    return await db.delete('todos', where: 'id = ?', whereArgs: [id]);
  }

  Future<int> deleteAllTodos() async {
    final db = await _databaseHelper.database;
    return await db.delete('todos');
  }
}
